<template>
  <div class="users-container">
    <TableModule :tableModule="tableModule" ref="TableModuleRef" @search="Search" @recover="Recover">
      <!-- 插入的新增按钮和删除按钮 -->
      <template #event>
        <el-button type="primary" @click="Add">新增</el-button>
        <el-button type="danger" @click="Delete">删除</el-button>
      </template>
      <!-- 插入表格的操作列 -->
      <template #tableColumn>
        <el-table-column align="center" fixed="right" label="操作" width="170">
          <template #default="scope">
            <el-button @click="Edit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="Delete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </TableModule>
    <!--  编辑对话框  -->
    <DialogModule :form-data="dialogModule" ref="dialogModuleRef" @confirm="Confirm" @cancel="Cancel" />
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, toRefs} from 'vue';
import { columnsData, queryData } from './dataModule/table.ts';
import {addUser, deleteUserById, getAllUsers, getRoleList, getUserInfoById, saveUserInfo} from '../../../api/user'
import {ElMessage, ElMessageBox} from "element-plus";
import { formColumns } from "./dataModule/form.ts";
import {User} from "../../../api/user/types/user.dto.ts";

// 表格
const state = reactive({
  columns: columnsData, // 表格配置
  query: queryData, // 查询条件配置
  queryForm: {
    username: '',
    role: '',
    startCreateTime: '',
    endCreateTime: '',
  }, // 查询form表单
  loading: false, // 加载状态
  dataList: [], // 列表数据
  pages: { // 分页数据
    total: 0,
    limit: 20,
    page: 1,
  }
})

const { loading, dataList, columns, pages, query, queryForm } = toRefs(state)

const TableModuleRef = ref() // 表格组件
const dialogModuleRef = ref<any>(null); // 编辑对话框组件

onMounted(() => {
  getDataList()// 获取列表信息
  setRoleInfo()// 获取角色下拉框的选项
})

// 传给子组件的
const tableModule = ref({
  editInputBlur: editInputBlur, // 可编辑单元的，失去焦点时的回调
  callback: getDataList, // 回调，子组件中可以看到很多调用callback的，这里对应的是获取列表数据的方法
  queryForm: queryForm,
  columns: columns,
  dataList: dataList,
  loading: loading,
  pages: pages,
  query: query,
})

// 获取列表信息
async function getDataList() {
  state.loading = true
  const res = await getAllUsers( {
    page: state.pages.page, limit: state.pages.limit, username: state.queryForm.username,
    role: state.queryForm.role, startCreateTime: state.queryForm.startCreateTime,
    endCreateTime: state.queryForm.endCreateTime })

  //返回数据后，将数据赋值给dataList，并修改分页信息，关闭加载状态
  state.loading = false
  if (res.code == 0) {
    state.dataList = res.data
    state.pages.total = res.count
  }
}

// 点击查询按钮时触发
function Search() {
  getDataList()
}

// 点击重置按钮时触发
function Recover() {
  state.queryForm = reactive({
    username: '',
    role: '',
    startCreateTime: '',
    endCreateTime: '',
  })
  getDataList();
}

function Add() { // 新增事件
  updateFields('createTime','isShow', false)
  updateFields('username','isEdit', false)
  updateOptions()
  dialogModule.value.dialogTitle = '新增用户'
  if (dialogModuleRef.value) {
    dialogModuleRef.value.showDialog(true)
  }
}

function Edit(row: any) { // 编辑事件
  updateOptions()
  dialogModule.value.dialogTitle = '编辑用户'
  getFormData(row.id)
  if (dialogModuleRef.value) {
    dialogModuleRef.value.showDialog(true)
  }
}

function Delete(row: any) { // 删除事件
  ElMessageBox.confirm(
      '此操作将永久删除该用户, 是否继续?',
      '提示',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' },
  ).then( async () => {
    const res = await deleteUserById(row.id)
    if (res.code == 200) {
      ElMessage({ message: '删除成功！', type: 'success' })
      getDataList()
    }else {
      ElMessage({ message: '删除失败！', type: 'error' })
    }
  }).catch(() => {
    ElMessage({ message: '取消了删除', type: 'info' });
  });
}

function editInputBlur() {
  console.log('失去焦点回调')
}

/**
 * 编辑表单模块
 */
const form = reactive({
  formColumn: formColumns
})

//使用 toRefs 将响应式对象转换为普通对象，其中每个属性都是一个 ref，不会失去响应性
const { formColumn } = toRefs(form)

// 传给子组件的
const dialogModule = ref({
  dialogTitle: '',
  columns: formColumn,
})

// 页面渲染角色字段类型
interface Role {
  id: number;
  label: string;
  value: number;
}
// 接口返回角色字段类型
interface RoleResult {
  id: number;
  name: string;
  description: string;
}
// 角色下拉框的选项
const options = ref<Role[]> ([])

// 获取角色下拉框的选项
async function setRoleInfo() {
  const roles = await getRoleList()
  if (roles.code == 0) {
    roles.data.forEach((item: RoleResult) => {
      if (item) {
        query.value[1].options.push({ id: item.id, label: item.description, value: item.id })
        options.value.push({ id: item.id, label: item.description, value: item.id })
      }
    })
  }
}

// 传入角色信息到新增、编辑对话框
function updateOptions() {
  for (let i = 0; i < formColumn.value.length; i++) {
    if (formColumn.value[i].prop == 'roleId') {
      formColumn.value[i].options = options.value
    }
  }
}

async function getFormData(id: string) {
  const res = await getUserInfoById(id);
  if (res.code == 200) {
    const data = res.data;
    // 遍历字段，将数据赋值给表单
    for (let i = 0; i < formColumn.value.length; i++) {
      const prop = formColumn.value[i].prop;
      if (data.hasOwnProperty(prop)) {
        formColumn.value[i].value = data[prop];
      }
    }
  }
}

// 动态更新表单信息，用于编辑对话框
function updateFields(prop: string, fields: string, newValue: any) {
  // 遍历字段，将数据赋值给表单
  for (let i = 0; i < formColumn.value.length; i++) {
    if (prop===formColumn.value[i].prop) {
      switch (fields) {
        case 'isShow':
          formColumn.value[i].isShow = newValue;
          break;
        case 'isEdit':
          formColumn.value[i].isEdit = newValue;
          break;
      }
    }
  }
}

const Confirm = async (operationType: number) => {
  const formData = dialogModule.value.columns
  // 使用 reduce 方法将数组转换为对象
  const formValues: { [key: string]: any } = formData.reduce((acc: any, item: any) => {
    acc[item.prop] = item.value;
    return acc;
  }, {});

  if (operationType == 1) {
    const res = await addUser(<User>formValues)
    if (res.code == 200) {
      ElMessage({message: '添加成功', type: 'success'})
    }else {
      ElMessage({ message: '添加失败', type: 'error' })
    }
  }else if (operationType == 2) {
    const res = await saveUserInfo(<User>formValues)
    if (res.code == 200) {
      ElMessage({ message: '保存成功', type: 'success' })
      getDataList()
    } else {
      ElMessage({ message: '保存失败', type: 'error' })
    }
  }
  clearFormValue()
};

const Cancel = () => {
  clearFormValue()
};

// 清空表单 TODO 待优化
const clearFormValue = () => {
  formColumn.value.forEach((item: any) => {
    item.value = '';
  });
}

</script>

<style scoped>
  .users-container {
    padding: 10px;
    background-color: white;
    height: 100%;
  }

  .diary {
    display: flex;
    align-items: center;
  }

  .diary:hover {
    cursor: pointer;
    background-color: gainsboro;
  }
</style>